package com.app.util;

import org.springframework.util.StringUtils;
import java.util.*;
import javax.servlet.ServletRequest;

/**
 * 帮助前端在使用jquery datatables 的情况下，进行后端排序
 *
 * @author zwxu
 */
public abstract class DataTablesQuery {

	public String toSortQL(String ql, Map<String, String> params) {
		String sortCol = params.get("iSortCol_0");
		String sortDir = params.get("sSortDir_0");
		String sColumns = params.get("sColumns");
		if (StringUtils.isEmpty(sortCol)) {
			return ql;
		}
		int sortIndex = 0;
		try {
			sortIndex = Integer.parseInt(sortCol);
		} catch (NumberFormatException e) {
			return ql;
		}

		if (StringUtils.isEmpty(sortDir)) {
			return ql;
		}
		sortDir = sortDir.equalsIgnoreCase("asc") ? "ASC" : "DESC";

		if (StringUtils.isEmpty(sColumns)) {
			return ql;
		}
		String[] cols = sColumns.split(",");
		if (sortIndex >= cols.length) {
			return ql;
		}
		String colName = cols[sortIndex];
		if (StringUtils.isEmpty(colName)) {
			return ql;
		}
		String pOrderStr = "\\s*(o|O)(r|R)(d|D)(e|E)(r|R)\\s+(b|B)(y|Y).*$";
		ql = ql.replaceFirst(pOrderStr, "");
		ql += " ORDER BY " + colName + " " + sortDir;
		return ql;
	}

	public Map<String, String> getParams(ServletRequest request) {
		Map<String, String> params = new HashMap<String, String>();
		if (request == null) {
			return params;
		}
		Enumeration<String> paramNames = request.getParameterNames();
		while (paramNames.hasMoreElements()) {
			String paramName = paramNames.nextElement();
			String paramValue = request.getParameter(paramName);
			params.put(paramName, paramValue);
		}
		return params;
	}

	public String toCountSQL(String sql) {
		if (null == sql || sql.trim().equals(""))
			return "";
		return "SELECT COUNT(*) FROM (" + sql + ") as COUNT";
	}

	/**
	 * 仅提供给本类和子类使用 需重写
	 * @param params,paramValues
	 * @return String
	 */
	protected abstract String buildQuery(Map<String, String> params, List<Object> paramValues);
}
